<template>
  <div class="page-wrapper">
    <div class="page-body">
      <div class="container-xl">
        <div class="row row-deck row-cards">
          <div class="col-12">
            <div class="card">
              <div class="card-header">
                <div class="d-flex">
                  <button class="btn btn-primary" @click="openRelationModal">
                    关系管理
                  </button>
                  <button class="btn btn-success ms-2" 
                          @click="connectRemoteMachines('/check')"
                          :disabled="!machineData || !hasSelectedItems(machineData)">
                    远程机器
                  </button>
                  <button class="btn btn-danger ms-2"
                          @click="connectRemoteMachines('/enforce')"
                          :disabled="!machineData || !hasSelectedItems(machineData)">
                    强制远程
                  </button>
                  <button class="btn btn-warning ms-2" 
                          @click="closeAllRemoteWindows">
                    关闭所有远程窗口
                  </button>
                </div>
                <div class="ms-auto text-secondary" v-if="machineInfo">
                    机器信息:
                    <div class="ms-2 d-inline-block">
                      <span class="info-text me-3">
                        机器IP: <span class="info-value">{{ machineInfo.ip }}</span>
                      </span>
                      <span class="info-text">
                        机器标签: <span class="info-value">{{ machineInfo.label }}</span>
                      </span>
                    </div>
                </div>
              </div>
              <div class="card-body border-bottom py-3">
                <div class="d-flex">
                  <div class="text-secondary">
                    {{ machineData ? machineData.length : 0 }} 条记录
                  </div>
                  <div class="ms-auto text-secondary">
                    搜索:
                    <div class="ms-2 d-inline-block">
                      <input type="text" 
                             class="form-control form-control-sm" 
                             v-model="searchQuery"
                             placeholder="请输入搜索内容"
                             @input="handleSearch">
                    </div>
                  </div>
                </div>
              </div>
              <div class="card-body">
                <div class="table-responsive">
                  <table class="table table-vcenter card-table">
                    <thead>
                      <tr>
                        <th>
                          <input class="form-check-input m-0 align-middle" 
                                 type="checkbox" 
                                 v-model="isAllChecked"
                                 @change="handleToggleAllCheckboxes">
                        </th>
                        <th class="w-1">关系ID</th>
                        <th class="w-1">机器ID</th>
                        <th>IP</th>
                        <th>标签</th>
                        <th>备注</th>
                        <th>状态</th>
                        <th>关联状态</th>
                        <th>最后修改时间</th>
                      </tr>
                    </thead>
                    <tbody>
                      <tr v-for="item in filteredData" 
                          :key="item.id"
                          @click="toggleRowCheckbox(machineData, item)"
                          :class="{'selected-row': item.checked}">
                        <td>
                          <input class="form-check-input m-0 align-middle" 
                                 type="checkbox" 
                                 v-model="item.checked">
                        </td>
                        <td><span class="text-secondary">{{ item.refId }}</span></td>
                        <td><span class="text-secondary">{{ item.id }}</span></td>
                        <td>{{ item.ip }}</td>
                        <td>{{ item.label }}</td>
                        <td>{{ item.remark }}</td>
                        <td>
                          <span :class="{
                            'badge': true,
                            'bg-green-lt': item.status === 1,
                            'bg-red-lt': item.status === 0
                          }">
                            {{ item.status === 1 ? '启用' : '禁用' }}
                          </span>
                        </td>
                        <td>
                          <span :class="{
                            'badge': true,
                            'bg-blue-lt': item.refId,
                            'bg-gray-lt': !item.refId
                          }">
                            {{ item.refId ? '已关联' : '未关联' }}
                          </span>
                        </td>
                        <td>{{ item.lastUpdateTime }}</td>
                      </tr>
                    </tbody>
                  </table>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- 关系管理对话框 -->
  <MachineRelationModal
    ref="relationModalRef"
    :sourceMachineId="sourceMachineId"
    :sourceMachineLabel="machineInfo?.label || ''"
    @save-success="searchData"
  />

  <!-- 提示组件 -->
  <ComponentModal
    ref="componentModalRef"
    :modalId="'modal-result'"
    :title="'操作结果'"
    :message="operationResult"
    :cancelText="'关闭'"
    :confirmText="'确定'"
  />

  <Loading ref="loadingRef" />
</template>

<script setup>
import { ref, onMounted, watch, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useTableMixin } from '@/mixins/tableMixin';
import MachineRelationModal from './MachineRelationModal.vue';
import ComponentModal from '@/components/ComponentModal.vue';
import Loading from '@/components/Loading.vue';

const apiBaseUrl = import.meta.env.VITE_API_BASE_URL;
const route = useRoute();
const router = useRouter();
const machineData = ref(null);
const isAllChecked = ref(false);
const sourceMachineId = ref('');
const searchQuery = ref('');
const relationModalRef = ref(null);
const machineInfo = ref(null);
const componentModalRef = ref(null);
const operationResult = ref('');
const loadError = ref(false);
const loadingRef = ref(null);

// 查询参数
const queryParams = ref({
  status: '1',
  label: 'py-vm'
});

const { 
  toggleAllCheckboxes,
  toggleRowCheckbox,
  getSelectedIds,
  hasSelectedItems,
  resetSelection 
} = useTableMixin();

// 过滤后的数据
const filteredData = computed(() => {
  if (!machineData.value) return [];
  if (!searchQuery.value) return machineData.value;
  
  const query = searchQuery.value.toLowerCase();
  return machineData.value.filter(item => 
    item.machineId.toString().includes(query) ||
    item.ip.toLowerCase().includes(query) ||
    item.label.toLowerCase().includes(query) ||
    (item.machineRemark && item.machineRemark.toLowerCase().includes(query))
  );
});

onMounted(() => {
  sourceMachineId.value = route.params.id;
  // 初始化时获取机器信息
  initData();
  // 初始化关系管理对话框
  relationModalRef.value.initModal();
});

// 初始化数据
const initData = async () => {
  try {
    await fetchMachineInfo();
    await searchData();
  } catch (error) {
    console.error('Error initializing data:', error);
    componentModalRef.value.openWarnModal('加载数据失败，请稍后重试！');
  }
};

// 获取机器基本信息
const fetchMachineInfo = async () => {
  try {
    const response = await fetch(`${apiBaseUrl}/resident/machine/getById/${sourceMachineId.value}`);
    const data = await response.json();
    if (data.success && data.result) {
      machineInfo.value = data.result;
    }
  } catch (error) {
    console.error('Error fetching machine info:', error);
    componentModalRef.value.openWarnModal('加载机器信息失败，请稍后重试！');
    // 设置一个默认的机器信息，避免后续操作报错
    machineInfo.value = {
      ip: '未知',
      label: '未知'
    };
  }
};

// 监听表格数据变化，更新全选状态
watch(machineData, () => {
  if (machineData.value) {
    isAllChecked.value = machineData.value.length > 0 && machineData.value.every(item => item.checked);
  }
}, { deep: true });

// 处理全选/全不选逻辑
const handleToggleAllCheckboxes = () => {
  if (machineData.value) {
    toggleAllCheckboxes(machineData.value, isAllChecked.value);
  }
};

// 处理搜索
const handleSearch = () => {
  // 搜索逻辑已通过计算属性实现
};

const searchData = async () => {
  if (!machineInfo.value) {
    console.error('Machine info not available');
    return;
  }

  machineData.value = null;
  try {
    const params = new URLSearchParams({
      sourceMachineId: sourceMachineId.value,
      relationType: machineInfo.value.label || '',
      onlyRef: true
    });
    const response = await fetch(`${apiBaseUrl}/resident/machine-ref/searchPyVmMachines?${params.toString()}`);
    const data = await response.json();
    if (data.success) {
      machineData.value = data.result.map(item => ({
        ...item,
        checked: false
      }));
    }
  } catch (error) {
    console.error('Error fetching machine data:', error);
  }
};

const toggleRelation = async (item) => {
  try {
    const response = await fetch(`${apiBaseUrl}/resident/machine/toggle-relation`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      body: new URLSearchParams({
        machineId: item.machineId,
        related: !item.related
      })
    });
    
    const data = await response.json();
    if (data.success) {
      item.related = !item.related;
    } else {
      console.error('Toggle relation failed:', data.message);
    }
  } catch (error) {
    console.error('Error toggling relation:', error);
  }
};

// 打开关系管理对话框
const openRelationModal = () => {
  relationModalRef.value.show();
};

// 文本截断函数
const truncateText = (text, length) => {
  if (!text) return '';
  return text.length > length ? text.substring(0, length) + '...' : text;
};

const truncatePluginName = (name) => {
  if (!name) return '';
  return name.length > 20 ? name.substring(0, 20) + '...' : name;
};

// 连接远程机器
const connectRemoteMachines = async (pathSuffix) => {
  // 只传递已选中的关系id（refId）
  const selectedIds = machineData.value
    .filter(item => item.checked)
    .map(item => item.refId)
    .filter(id => id);
  if (selectedIds.length === 0) {
    componentModalRef.value.openWarnModal('请选择已关联的机器');
    return;
  }

  const actionText = pathSuffix === '/enforce' ? '强制远程连接' : '远程连接';

  try {
    loadingRef.value.openLoading && loadingRef.value.openLoading(`正在${actionText}，请稍候...`);
    const response = await fetch(`${apiBaseUrl}/resident/machine-ref/connect-remote${pathSuffix}`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(selectedIds)
    });

    const data = await response.json();
    if (data.success) {
      // 以多行文本方式展示结果，便于阅读
      operationResult.value = data.result.join('\n');
      componentModalRef.value.openInfoModal('<pre>' + operationResult.value + '</pre>');
    } else {
      componentModalRef.value.openWarnModal(data.errorMsg || '操作失败');
    }
  } catch (error) {
    console.error('Error connecting to remote machines:', error);
    componentModalRef.value.openWarnModal('连接失败，请稍后重试');
  } finally {
    loadingRef.value.closeLoading && loadingRef.value.closeLoading();
  }
};

// 关闭所有远程窗口
const closeAllRemoteWindows = async () => {
  try {
    loadingRef.value.openLoading && loadingRef.value.openLoading('正在关闭所有远程窗口，请稍候...');
    const params = new URLSearchParams({
      machineId: sourceMachineId.value
    });
    const response = await fetch(`${apiBaseUrl}/resident/machine-ref/close-connect-remote?${params.toString()}`);

    const data = await response.json();
    if (data.success) {
      // 显示单个字符串结果
      operationResult.value = data.result;
      componentModalRef.value.openInfoModal(operationResult.value);
    } else {
      componentModalRef.value.openWarnModal(data.errorMsg || '操作失败');
    }
  } catch (error) {
    console.error('Error closing remote windows:', error);
    componentModalRef.value.openWarnModal('关闭失败，请稍后重试');
  } finally {
    loadingRef.value.closeLoading && loadingRef.value.closeLoading();
  }
};
</script>

<style scoped>
.text-muted {
  color: #6c757d;
}

.bg-green-lt {
  background-color: rgba(40, 167, 69, 0.15) !important;
  color: #2fb344 !important;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 0.875em;
}

.bg-red-lt {
  background-color: rgba(220, 53, 69, 0.15) !important;
  color: #d63939 !important;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 0.875em;
}

/* 添加选中行的样式 */
.selected-row {
  background-color: rgba(32, 107, 196, 0.1) !important;
}

tr {
  cursor: pointer;
  transition: background-color 0.2s ease;
}

tr:hover {
  background-color: rgba(32, 107, 196, 0.05);
}

/* 防止点击复选框时触发行点击事件 */
tr input[type="checkbox"] {
  cursor: pointer;
  pointer-events: auto;
}

/* 开关样式优化 */
.form-switch {
  padding-left: 2.5em;
}

.form-switch .form-check-input {
  width: 2.5em;
  margin-left: -2.5em;
  background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='-4 -4 8 8'%3e%3ccircle r='3' fill='rgba%280, 0, 0, 0.25%29'/%3e%3c/svg%3e");
  background-position: left center;
  border-radius: 2em;
  transition: background-position .15s ease-in-out;
}

.form-switch .form-check-input:checked {
  background-position: right center;
  background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='-4 -4 8 8'%3e%3ccircle r='3' fill='%23fff'/%3e%3c/svg%3e");
}

.form-switch .form-check-input:focus {
  border-color: rgba(0, 0, 0, 0.25);
  outline: 0;
  box-shadow: 0 0 0 0.2rem rgba(0, 0, 0, 0.25);
}

.form-switch .form-check-input:checked {
  background-color: #206bc4;
  border-color: #206bc4;
}

/* 搜索框样式 */
.form-control-sm {
  height: calc(1.5em + 0.5rem + 2px);
  padding: 0.25rem 0.5rem;
  font-size: 0.875rem;
  border-radius: 0.2rem;
}

/* 按钮样式优化 */
.btn {
  padding: 0.375rem 0.75rem;
  font-size: 0.875rem;
  line-height: 1.5;
  border-radius: 0.2rem;
  transition: all 0.15s ease-in-out;
}

.btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.bg-blue-lt {
  background-color: rgba(32, 107, 196, 0.15) !important;
  color: #206bc4 !important;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 0.875em;
}

.bg-gray-lt {
  background-color: rgba(108, 117, 125, 0.15) !important;
  color: #6c757d !important;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 0.875em;
}

/* 表格列宽优化 */
.table th:nth-child(1) { width: 40px; }   /* 复选框列 */
.table th:nth-child(2) { width: 80px; }   /* 关系ID列 */
.table th:nth-child(3) { width: 80px; }   /* 机器ID列 */
.table th:nth-child(4) { width: 120px; }  /* IP列 */
.table th:nth-child(5) { width: 100px; }  /* 标签列 */
.table th:nth-child(6) { width: 150px; }  /* 备注列 */
.table th:nth-child(7) { width: 80px; }   /* 状态列 */
.table th:nth-child(8) { width: 80px; }   /* 关联状态列 */
.table th:nth-child(9) { width: 150px; }  /* 最后修改时间列 */

/* 机器信息样式 */
.machine-info {
  display: flex;
  align-items: center;
  gap: 1.5rem;
  padding: 0.25rem 0.5rem;
  background-color: rgba(32, 107, 196, 0.05);
  border-radius: 0.2rem;
  font-size: 0.875rem;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  white-space: nowrap;
}

.info-label {
  color: #6c757d;
  font-size: 0.875rem;
}

.info-value {
  color: #206bc4;
  font-size: 0.875rem;
  padding: 0.25rem 0.5rem;
  background-color: rgba(32, 107, 196, 0.1);
  border-radius: 0.2rem;
}

.info-text {
  font-size: 0.875rem;
  color: #6c757d;
}

.info-value {
  color: #206bc4;
  font-weight: 500;
  padding: 0.125rem 0.375rem;
  background-color: rgba(32, 107, 196, 0.1);
  border-radius: 0.2rem;
  margin-left: 0.25rem;
}
</style> 